package com.yuchao.base.xyc005;

/**
 * @description: 讨巧的方案
 * 要输出的时候判断一下当前需要输出的数是不是自己要负责打印的值，如果是就输出，不是就直接释放锁。
 * @author: xingyuchao
 * @date: 2019-11-25
 */
public class Test {

    private int count = 0;

    private final Object lock = new Object();


    public void turning() {

        Thread even = new Thread(() -> {
            while (count < 100) {
                synchronized (lock) {
                    // 只处理偶数
                    if ((count & 1) == 0) {
                        System.out.println(Thread.currentThread().getName() + ": " + count++);
                    }
                }
            }
        }, "偶数");


        Thread odd = new Thread(() -> {
            while (count < 100) {
                synchronized (lock) {
                    // 只处理奇数
                    if ((count & 1) == 1) {
                        System.out.println(Thread.currentThread().getName() + ": " + count++);
                    }
                }
            }
        }, "奇数");


        even.start();
        odd.start();
    }


    public static void main(String[] args) {
        new Test().turning();
    }

}


